import Taro, { Component } from '@tarojs/taro'
import {View, Image, Text, ScrollView} from '@tarojs/components'
import {connect} from "@tarojs/redux";
import { asyncLoadAddressList, selectAddress } from '../../actions/address'

import './index.styl'

@connect(({ address, user }) => ({
  address, user
}), (dispatch) => ({
  // 加载地址列表
  onLoadAddressList(shop_only = false) {
    dispatch(asyncLoadAddressList(shop_only))
  },
  // 选中地址
  onSelectAddress(select_id) {
    dispatch(selectAddress(select_id))
  }
}))
class Address extends Component {
  constructor () {
    super(...arguments)
    this.state = {
    }
  }
    config = {
    navigationBarTitleText: '管理收货地址'
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
  }

  /**
   * 新增/编辑收货地址
   * @param {string} id 地址id 或者是 'new' 代表新增
   */
  addAddress (id, event) {
    event.preventDefault()
    event.stopPropagation()
    // 跳转到目的页面，在当前页面打开
    const from = this.$router.params.from || 'addressList'
    Taro.navigateTo({
      url: `/pages/address/edit?edit=${id}&from=${from}`
    })
  }
  // 选择地址
  selectAddress (id) {
    const from = this.$router.params.from
    const canSelect = from === 'settle'
    if (!canSelect) return
    this.props.onSelectAddress(id)
    Taro.navigateBack({ delta: 1 })
  }

  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }

  componentDidMount () {
  }
  componentWillUnmount () { }

  componentDidShow () {
    const from = this.$router.params.from
    this.props.onLoadAddressList(from === 'settle')
  }

  componentDidHide () { }

  render () {
    const { addressList } = this.props.address
    // TODO 数据为空的处理
    const renderList = addressList.map((item, index) => {
      return (<View className='item' key={index} onClick={this.selectAddress.bind(this, item.id)}>
        <View className='addr'>
          <View className='street'>
            {item.tag && <Text className='tag'>{item.tag}</Text>}
            <Text className='stress-value'>{item.address}</Text>
          </View>
          <View className='detail'>
            {item.gatenum}
          </View>
          <View className='contact'>
            <Text className='name'>{item.truename}</Text>
            <Text className='tel'>{item.phone}</Text>
          </View>
        </View>
        <Text className='shopfont shop-edit edit' onClick={this.addAddress.bind(this, item.id)} />
      </View>)
    })
    return (
      <View className='address'>
        <ScrollView
          className='list'
          enableBackToTop
          scrollY
          scrollWithAnimation
          scrollTop='0'
        >
          {renderList}
        </ScrollView>
        <View className='bottom'>
          <Text className='add' onClick={this.addAddress.bind(this, 'new')}>新增</Text>
        </View>
      </View>
    )
  }
}

export default Address
